import { defineStore } from 'pinia'
import { store } from '../index'
import router from '@/router'

interface UserInfo {
  username: string
}

interface UserState {
  userInfo?: UserInfo
  token: string
}

export const useUserStore = defineStore('user', {
  state: (): UserState => {
    return {
      userInfo: undefined,
      token: '',
    }
  },
  getters: {
    getToken(): string {
      return this.token
    },
    getUserInfo(): UserInfo | undefined {
      return this.userInfo
    },
  },
  actions: {
    setToken(token: string) {
      this.token = token
    },
    setUserInfo(userInfo?: UserInfo) {
      this.userInfo = userInfo
    },
    reset() {
      this.setToken('')
      this.setUserInfo(undefined)
      router.replace('/login')
    },
    logout() {
      this.reset()
    },
  },
  persist: true,
})

export const useUserStoreWithOut = () => {
  return useUserStore(store)
}
